#pragma once
#include <iostream>
#include <string>

#include <netinet/in.h>
#include <netinet/ip.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <memory>
#include "MyCommon.hpp"
#include "MyInertAddr.hpp"
#include "Log.hpp"
using namespace LogModule;
using namespace CommonModule;
static const int gbacklogg = 8;

namespace SocketMoudule
{
    // using namespace std;
    class Socket
    {
    public:
        virtual void SocketOrDie() = 0;
        virtual void BindOrDie(uint16_t) = 0;
        virtual void ListenOrDie(int) = 0;
        virtual std::shared_ptr<Socket> Accept(InertAddr *) = 0;
        virtual void Close() = 0;
        virtual int Recv(std::string *) = 0;                     // 接收数据
        virtual int Send(std::string &) = 0;                     // 发送数据
        virtual void Connect(const std::string &, uint16_t) = 0; // 连接服务器
    public:                                                      // 便捷方法
        void BuildTcpServerMoudule(uint16_t port, int backlog = gbacklogg)
        {
            SocketOrDie();        // 1. 创建套接字
            BindOrDie(port);      // 2. 绑定端口
            ListenOrDie(backlog); // 3. 开始监听
        }

        void BuildUdpServerMoudule()
        {
            void SocketOrDie(); // 1. 创建套接字
            void BindOrDie();   // 2. 绑定端口
        }
    };

    class TcpSocket : public Socket
    {
    private:
        int _socketfd;

    public:
        TcpSocket(int socketfd = -1) : _socketfd(socketfd)
        {
        }
        // 创建Tcp套接字
        virtual void SocketOrDie() override
        {
            _socketfd = socket(AF_INET, SOCK_STREAM, 0);
            if (_socketfd < 0)
            {
                LOG(LogLevel::FATAL) << "Socket fail"; // 记录致命错误
                exit(SOCKET_ERROR);                    // 退出程序
            }
            LOG(LogLevel::INFO) << "socket success";
        }
        // 绑定地址
        virtual void BindOrDie(uint16_t port) override
        {
            InertAddr addr(port); // 创建地址对象(任意指定端口)
            int n = bind(_socketfd, (struct sockaddr *)&addr.getaddr(), sizeof(addr.getaddr()));
            if (n < 0)
            {
                LOG(LogLevel::FATAL) << "bind fail";
                exit(BIND_ERRO);
            }
            LOG(LogLevel::INFO) << "Bind success";
        }
        // 开始监听
        virtual void ListenOrDie(int backlog) override
        {
            int n = listen(_socketfd, backlog);
            if (n < 0)
            {
                LOG(LogLevel::FATAL) << "Listen fail";
                exit(LISTEN_ERRO);
            }
            LOG(LogLevel::INFO) << "Listen success";
        }

        // 接受连接
        virtual std::shared_ptr<Socket> Accept(InertAddr *addr) override
        {
            socklen_t len = sizeof(sockaddr_in);
            sockaddr_in peer; // 存储对端地址
            int n = accept(_socketfd, (sockaddr *)&peer, &len);
            if (n < 0)
            {
                LOG(LogLevel::WARNING) << addr->StringAddr() << "accept fail";
                return nullptr; // 返回空指针表示失败
            }
            *addr = InertAddr(peer);               // 保存对端地址信息
            return std::make_shared<TcpSocket>(n); // 返回新连接的智能指针
        }
        // 关闭套接字
        virtual void Close() override
        {
            close(_socketfd);
        }

        // 接收数据
        virtual int Recv(std::string *out) override
        {
            char buffer[1024];                                   // 1KB缓冲区
            int n = read(_socketfd, buffer, sizeof(buffer) - 1); // 保留1字节给结束符
            if (n > 0)
            {
                buffer[n] = '\0'; // 添加字符串结束符
                *out += buffer;   // 追加到输出字符串
            }
            return n; // 返回读取的字节数
        }

        // 发送数据
        virtual int Send(std::string &message) override
        {
            return write(_socketfd, message.c_str(), message.size());
        }

        // 连接服务器
        virtual void Connect(const std::string &ip, uint16_t port) override
        {
            InertAddr addr(ip, port); // 创建目标地址对象
            int n = connect(_socketfd, (struct sockaddr *)&addr.getaddr(), sizeof(addr.getaddr()));
            if (n < 0)
            {
                LOG(LogLevel::FATAL) << "connect fail";
                exit(CONNECT_ERRO);
            }
            LOG(LogLevel::INFO) << "connect success";
        }
    };
}